package erp

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"net/url"

	"mall/service/backend/api/internal/logic/backend/erp"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils/erpurlparse"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 库存变更通知
func NewInventoryChangeCallbackHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		resp := &types.ErpCallbackResp{
			Success:  false,
			ErrorMsg: "fail",
		}

		defer r.Body.Close()
		var buffer bytes.Buffer
		_, err := io.Copy(&buffer, r.Body)
		if err != nil {
			logx.Errorw("[ERP InventoryChangeCallback] Error reading response:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("InventoryChangeCallbackHandler : %+v ", buffer.String())
		// app_key=T3854962145\u0026data=%7B%22item_id%22%3A%2247%22%2C%22sku_id%22%3A%2298%22%2C%22quantity%22%3A10%2C%22shop_nick%22%3A%22shop1820%22%7D\u0026format=json\u0026sign=4260640DFB11FB83BA47E957E3EF4C30\u0026timestamp=1737022989595

		str, err := url.QueryUnescape(buffer.String())
		// str := erpurlparse.ParseAsciiToString(string(buffer.Bytes()))
		if err != nil {
			logx.Errorw("[ERP InventoryChangeCallback] Error url.QueryUnescape:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("InventoryChangeCallbackHandler url.QueryUnescape: %+v ", str)
		// app_key=T3854962145\u0026data={\"item_id\":\"47\",\"sku_id\":\"98\",\"quantity\":10,\"shop_nick\":\"shop1820\"}\u0026format=json\u0026sign=4260640DFB11FB83BA47E957E3EF4C30\u0026timestamp=1737022989595

		data, ok := erpurlparse.Parse(str, svcCtx.Config.Erp.AppKey, svcCtx.Config.Erp.Secret)
		if !ok {
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("InventoryChangeCallbackHandler data : %+v ", data)
		// {\"item_id\":\"47\",\"sku_id\":\"98\",\"quantity\":10,\"shop_nick\":\"shop1820\"}

		var req types.InventoryChangeCallbackReq
		if err = json.Unmarshal([]byte(data), &req); err != nil {
			logx.Errorw("[ERP InventoryChangeCallback] Error json.Unmarshal:", logx.Field("detail", err.Error()))
			httpx.OkJsonCtx(ctx, w, resp)
			return
		}

		logx.Infof("InventoryChangeCallbackHandler req : %+v ", req)
		// {ItemId:0xc001519130 Quantity:0xc00169d0a8 ShopNick:0xc001519150 SkuId:0xc001519140}

		l := erp.NewInventoryChangeCallbackLogic(ctx, svcCtx)
		ret, err := l.InventoryChangeCallback(&req)
		if err != nil {
			logx.Errorw("[ERP InventoryChangeCallback] Error:", logx.Field("detail", err.Error()))
		}
		httpx.OkJsonCtx(ctx, w, ret)
	}
}
